package com.nebula.api.interceptors;

import com.nebula.api.common.entity.TokenUser;
import com.nebula.api.utils.RedisUtils;
import com.nebula.commons.redis.RedisKeys;
import link.ahsj.core.entitys.CodeMsg;
import link.ahsj.core.exception.ErrorCode;
import link.ahsj.core.utils.base.AppAssertUtil;
import link.ahsj.core.utils.str.UrlUtils;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author Eastern unbeaten
 * @email chenshiyun2011@163.com
 * @data 2019/3/7
 */
@Component
@Log
public class UserInterceptor implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${app.filter.path}")
    private String filterPath;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(TokenUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);


        //获取当前访问url
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        TokenUser userInfo = null;
        //校验非过滤url
        if (!UrlUtils.checkURL(filterPath, requestURI, contextPath)) {
            log.info("url:" + requestURI + " ,赋值了用户信息");
            // 获取token校验
            String token = request.getHeader(Interceptor.X_AUTH_TOKEN);
            //没有登录获取接口直接抛出异常
            AppAssertUtil.isBlank(token, ErrorCode.LOGIN, CodeMsg.NOT_TOKEN);
            userInfo = redisUtils.get((RedisKeys.getAppToken(token)), TokenUser.class);
        }
        return Objects.nonNull(userInfo) ? userInfo : new TokenUser();
    }
}
